package me.duzhi.blog.plugins.history;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import io.jpress.message.Message;
import io.jpress.message.MessageListener;
import io.jpress.message.annotation.Listener;
import io.jpress.model.Content;
import io.jpress.model.Metadata;
import io.jpress.model.Taxonomy;
import io.jpress.model.query.MappingQuery;
import io.jpress.model.query.TaxonomyQuery;
import io.jpress.utils.HttpUtils;
import io.jpress.utils.StringUtils;
import me.duzhi.blog.hanlder.HtmlHandler;

import java.math.BigInteger;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ashang.peng@aliyun.com
 * @date 一月 23, 2017
 */
@Listener(action = {HistoryListener.ACTION_LOAD_HISTORY})
public class HistoryListener implements MessageListener {
    public static final String ACTION_LOAD_HISTORY = "load_history";
    private static String QUERY_URL = "http://v.juhe.cn/todayOnhistory/queryEvent.php";
    public static String QUERY_KEY = "613f744006b1e8cfc47574144683acd8";
    public static String QUERY_CONTENT_URL = "http://v.juhe.cn/todayOnhistory/queryDetail.php";
    private static final String TAG_SPLIT = "HisTag";

    @Override
    public void onMessage(Message message) {
        String ut = HtmlHandler.before_date;
        Taxonomy before = TaxonomyQuery.me().findBySlugAndModule(getSulg(TAG_SPLIT+ut),"history");
        if (before != null) {
            return;
        }
        try {
            Boolean succ = Db.tx(new IAtom() {
                @Override
                public boolean run() throws SQLException {
                    Map map = getDefaultParams();
                    map.put("date", HtmlHandler.SIMPLE_DATE_FORMAT.format(new Date()));
                    Taxonomy taxonomy = new Taxonomy();
                    taxonomy.setSlug(TAG_SPLIT+ut);
                    taxonomy.setCreated(new Date());
                    taxonomy.setTitle(ut);
                    taxonomy.setType(Taxonomy.TYPE_TAG);
                    taxonomy.setContentModule("history");
                    taxonomy.save();
                    try {
                        saveEventList(map,taxonomy);
                    } catch (Exception e) {
                        return false;
                    }
                    return true;
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getSulg(String slug) {
        if (StringUtils.isNotBlank(slug)) {
            slug = slug.trim();
            if (StringUtils.isNumeric(slug)) {
                slug = "t" + slug; // slug不能为全是数字,随便添加一个字母，t代表taxonomy好了
            } else {
                slug = slug.replaceAll("\\pP|\\pS|(\\s+)|[\\$,。\\.…，_？\\-?、；;:!]", "");
            }
        }
        return slug;
    }

    private void saveEventList(Map map,Taxonomy taxonomy) throws Exception {
        JSONObject object = getJsonFromURL(QUERY_URL, map);
        if ("success".equals(object.getString("reason"))) {
            JSONArray resultArray = object.getJSONArray("result");
            for (int i = 0; i < resultArray.size(); i++) {
                JSONObject result = (JSONObject) resultArray.get(i);
                String createDate = result.getString("date");
                Map params = getDefaultParams();
                params.put("e_id", result.getString("e_id"));
                JSONObject contentObject = getJsonFromURL(QUERY_CONTENT_URL, params);
                if ("success".equals(contentObject.getString("reason"))) {
                    JSONArray contentArray = contentObject.getJSONArray("result");
                    JSONObject content = (JSONObject) contentArray.get(0);
                    Content content1 = new Content();
                    content1.setCreated(new Date());
                    content1.setUserId(new BigInteger("1"));
                    content1.setStatus(Content.STATUS_NORMAL);
                    content1.setTitle(content.getString("title"));
                    String text = content.getString("content");
                    text =  text.replaceAll("\r|\n", "</br>");
                    content1.setText(text);
                    content1.setModule("history");
                    content1.getTaxonomys();
                    content1.save();
                    Metadata metadata = new Metadata();
                    metadata.setMetaKey("historyDate");
                    metadata.setMetaValue(createDate);
                    metadata.setObjectId(content1.getId());
                    metadata.setObjectType("history");
                    metadata.save();
                    MappingQuery.me().doBatchUpdate(content1.getId(),new BigInteger[]{taxonomy.getId()});
                }
            }
        }
    }

    /**
     * get Default Map
     *
     * @return
     */
    private Map getDefaultParams() {
        Map params = new HashMap();
        params.put("key", QUERY_KEY);
        return params;
    }

    /**
     * 获取返回对象为Json
     *
     * @param url
     * @param map
     * @return
     * @throws Exception
     */
    private JSONObject getJsonFromURL(String url, Map map) throws Exception {
        Map  header = getDefaultParams();
        header.put("contentType", "application/json;UTF-8");
        header.put("Charsert","UTF-8");
        String eventResult = HttpUtils.get(url, map,header);
        return (JSONObject) JSON.parse(eventResult);
    }

    public static void main(String[] args) {
        new HistoryListener().onMessage(null);
    }
}
